package penguin.masking.jdbc;

import penguin.masking.Logger;
import penguin.masking.StringUtil;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;

/**
 * @author wuxh
 * @version 1.0.0
 */
public class MysqlMetaHandler extends AbstractDBMetaHandler {

    @Override
    public String tableName(ResultSet set, final int columnIndex) {
        String tableName = null;
        try {
            final ResultSetMetaData resultSetMetaData = resultSetMetaData(set);
            tableName = resultSetMetaData.getTableName(columnIndex);
        } catch (Exception e) {
            e.printStackTrace();
            Logger.error("表名获取异常!", e);
        }
        if (StringUtil.isEmpty(tableName)) {
            throw new RuntimeException("数据库驱动不支持表名查询！");
        }
        return tableName;
    }

    @Override
    public String userName(ResultSet set) {
        try {
            final Connection connection = set.getStatement().getConnection();
            String user = doCheck(new LoopCallCheck<String>() {
                @Override
                public String hashValue() {
                    return "userName-" + connection.toString();
                }

                @Override
                public String call() throws Exception {
                    return connection.getMetaData().getUserName();
                }
            });
            int i = user == null ? -1 : user.indexOf("@");//解决mysql host user会带有@问题
            return i == -1 ? user : user.substring(0, i);
        } catch (Exception e) {
            e.printStackTrace();
            Logger.error("用户获取异常!", e);
        }
        return null;
    }

    @Override
    public String catalogName(final ResultSet set, final int columnIndex) {
        String catalogName = null;
        try {
            catalogName = resultSetMetaData(set).getCatalogName(columnIndex);
        } catch (Exception e) {
            e.printStackTrace();
            Logger.error("catalogName获取异常!", e);
        }
        if (StringUtil.isEmpty(catalogName)) {
            throw new RuntimeException("数据库驱动不支持数据库名查询！");
        }
        return catalogName;
    }
}
